# coding:utf-8

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code: "+str(rc))

    client.subscribe("robot/#")

def on_message(client, userdata, msg):
    try:
        if msg.topic == "robot/str":
            print(userdata, msg.topic, msg.payload.decode("utf8"))
        elif msg.topic == "robot/json":
            print(userdata,msg.topic,msg.payload.decode("utf8"))
        else:
            print(userdata,msg.topic,len(msg.payload))
    except Exception as err:
        print("on_message error:",err)
        pass

def subtopic():
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message

    client.username_pw_set("test","testpwd")
    # client.connect("remote.xxxx.com",8080)
    # http://www.sx-ck.com:8161/admin/topics.jsp
    # client.connect("http://www.sx-ck.com", 8161)
    client.connect("tcp://www.sx-ck.com", 61614)

    client.publish("robot/python","Hello!!") # 发送消息
    client.loop_forever()
    pass

if __name__=="__main__":
    subtopic()
    pass